<template>
  <view class="profile-page">
    <!-- 顶部留白区域 -->
    <view class="top-margin"></view>

    <!-- 个人信息区域 -->
    <view class="profile-header" v-if="userInfo">
      <view class="profile-bg" :style="profileBgStyle"></view>
      <view class="profile-content">
        <up-avatar class="avatar" shape="circle" size="140rpx" :src="userInfo.avatar"></up-avatar>
        <view class="base-info">
          <text class="nickname">{{ userInfo.nickname }}</text>
          <text class="id-ip">ID:{{ userInfo.userId }} | 金币:{{ userInfo.coin || 0 }}</text>
        </view>
        <view class="stats-actions">
          <text class="view-count">{{ viewCount }}人浏览</text>
          <view class="action-buttons">
            <up-button class="btn-private" size="mini" shape="round" color="#007AFF" @click="navigateToChat">私聊
            </up-button>
            <up-button class="btn-block" size="mini" shape="round" bg-color="#F5F5F5" text-color="#333">拉黑</up-button>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view class="loading" v-else>
      <up-icon name="loading" size="40rpx" color="#999"></up-icon>
      <text>加载中...</text>
    </view>

    <!-- 学校和简介 -->
    <view class="profile-intro" v-if="userInfo">
      <text class="school-grade">{{ userInfo.school || '未知学校' }} {{ userInfo.campus || '未知校区' }}
        {{ userInfo.grade || '未知年级' }}
      </text>
      <text class="self-intro">{{ userInfo.appraise || '该用户还没有填写个人简介' }}</text>
    </view>

    <!-- 标签栏 -->
    <view class="custom-tab-bar">
      <view
          class="tab-item"
          v-for="(item, index) in tabList"
          :key="index"
          @click="handleTabClick(index)"
          :class="{ active: currentTab === index }"
      >
        <text class="tab-text">{{ item.name }}</text>
        <view class="tab-active-line" v-if="currentTab === index"></view>
      </view>
    </view>

    <!-- 标签内容区域 -->
    <view v-if="currentTab === 0" class="tab-content">
      <UserPosts :userInfo="userInfo" :userPosts="userPosts"/>
    </view>
    <view v-else-if="currentTab === 1" class="tab-content">
      <text class="tab-text">这是闲置</text>
    </view>
    <view v-else-if="currentTab === 2" class="tab-content">
      <text class="tab-text">这是任务</text>
    </view>
    <view v-else-if="currentTab === 3" class="tab-content">
      <text class="tab-text">这是接单</text>
    </view>
    <view v-else class="tab-content">
      <text class="tab-text">这是印象</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import {ref, computed, onMounted, onBeforeMount} from 'vue';
import {getUserInfoById, getUserPosts} from '@/apis/userAPI';
import UserPosts from '@/components/user-published/user-published.vue';
import {UAvatar, UButton, UIcon} from 'uview-plus';
import {onLoad} from '@dcloudio/uni-app';

// 响应式数据
const userInfo = ref<any>(null);
const viewCount = ref(0);
const currentTab = ref(0);
const tabList = ref([
  {name: '帖子(0)'},
  {name: '闲置(0)'},
  {name: '任务(0)'},
  {name: '接单(0)'},
  {name: '印象(0)'}
]);
const userPosts = ref<any[]>([]);

onLoad((options) => {
  if (options.currentTab) {
    currentTab.value = parseInt(options.currentTab);
  }
})

// 头像背景样式
const profileBgStyle = computed(() => {
  if (!userInfo.value) return {};
  return {
    backgroundImage: `url("${userInfo.value.avatar}")`,
    backgroundSize: 'cover',
    backgroundPosition: 'center',
    opacity: 0.45,
    filter: 'blur(2px)'
  };
});

// 获取 URL 参数
const getQueryParams = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  return currentPage.options || {};
};

// 初始化数据
onBeforeMount(() => {
  const params = getQueryParams();
  let userId = Number(params.userId);
  if (isNaN(userId) || userId <= 0) {
    userId = 1;
  }
  initData(userId);
});

const initData = async (userId: number) => {
  try {
    // 获取用户信息
    const userResponse: any = await getUserInfoById(userId);
    if (userResponse.data?.code === 200) {
      userInfo.value = userResponse.data.data;
      viewCount.value = userResponse.data.data?.viewCount || 0;
    } else {
      uni.showToast({title: '获取用户信息失败', icon: 'none'});
    }

    // 获取用户帖子
    const postsResponse: any = await getUserPosts(userId);
    if (postsResponse.data?.code === 200) {
      userPosts.value = postsResponse.data.data || [];
      tabList.value[0].name = `帖子(${userPosts.value.length})`;
    } else {
      uni.showToast({title: '获取帖子列表失败', icon: 'none'});
    }
  } catch (error) {
    console.error('数据加载失败:', error);
    uni.showToast({title: '网络错误', icon: 'none'});
  }
};

// 标签点击处理
const handleTabClick = (index: number) => {
  currentTab.value = index;
  console.log('切换到标签:', index);
};
// 定义导航到聊天页面的方法
const navigateToChat = () => {
  if (userInfo.value) {
    uni.navigateTo({
      url: `/pages/message/chat?userId=${userInfo.value.userId}&name=${userInfo.value.nickname}&avatar=${userInfo.value.avatar}`
    });
  }
};
</script>

<style scoped lang="scss">
.profile-page {
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 20rpx;

  .top-margin {
    height: 40rpx;
    width: 100%;
  }

  .profile-header {
    position: relative;
    width: 100%;
    padding: 60rpx 20rpx 30rpx;
    box-sizing: border-box;
    margin: 0 15rpx 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

    .profile-bg {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 0;
    }

    .profile-content {
      position: relative;
      z-index: 1;
      display: flex;
      flex-direction: column;
      align-items: center;

      .avatar {
        border: 6rpx solid #fff;
        margin-bottom: 25rpx;
        box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
      }

      .base-info {
        text-align: center;
        margin-bottom: 20rpx;

        .nickname {
          font-size: 36rpx;
          font-weight: bold;
          color: #333;
          display: block;
          margin-bottom: 8rpx;
        }

        .id-ip {
          font-size: 24rpx;
          color: #555;
        }
      }

      .stats-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        max-width: 500rpx;

        .view-count {
          font-size: 24rpx;
          color: #666;
        }

        .action-buttons {
          display: flex;
          gap: 15rpx;

          .btn-private, .btn-block {
            padding: 0 25rpx;
            height: 52rpx;
            line-height: 52rpx;
          }
        }
      }
    }
  }

  .loading {
    text-align: center;
    padding: 50rpx 0;
    color: #999;
    font-size: 24rpx;
  }

  .profile-intro {
    padding: 0 20rpx;
    margin: 0 15rpx 20rpx;

    .school-grade {
      font-size: 26rpx;
      color: #333;
      display: block;
      margin-bottom: 10rpx;
    }

    .self-intro {
      font-size: 24rpx;
      color: #666;
      line-height: 1.6;
    }
  }

  .custom-tab-bar {
    display: flex;
    margin: 0 15rpx 20rpx;
    background-color: #f9f9f9;
    border-radius: 10rpx;
    height: 80rpx;

    .tab-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      position: relative;

      .tab-text {
        font-size: 26rpx;
        color: #666;
      }

      &.active {
        .tab-text {
          color: #007AFF;
          font-weight: bold;
        }
      }
    }

    .tab-active-line {
      position: absolute;
      bottom: 0;
      width: 70%;
      height: 4rpx;
      background-color: #007AFF;
    }
  }

  .tab-content {
    padding: 30rpx 20rpx;
    min-height: 300rpx;
  }

  .tab-text {
    font-size: 28rpx;
    color: #666;
  }
}
</style>